package com.ifcreate.infowell.common.config;

import com.google.gson.Gson;
import com.ifcreate.infowell.common.annotation.JsonConvert;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Author chenzedeng
 * @Email yustart@foxmail.com
 * @Create 2020-09-03 4:20 下午
 */
public class JsonConvertHandleResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonConvert.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        JsonConvert annotation = parameter.getParameterAnnotation(JsonConvert.class);
        String json = webRequest.getParameter(annotation.value());
        if (StringUtils.isBlank(json)) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(json, annotation.cls());
    }
}
